﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using NetFluid;
using Sito.Model;

namespace Sito.Logic
{
    class StatManager:FluidController
    {
        public override bool Blocking
        {
            get { return false; }
            set { base.Blocking = value; }
        }

        private static ulong[] Pages;

        //Dimensione del campione
        private static int size = 20;

        public override void OnServerStart()
        {
            Pages=new ulong[5000/size];

            NetFluid.Core.Engine.StopWatch = x =>
            {
                ThreadPool.QueueUserWorkItem(y =>
                {
                    var k = (int)decimal.Truncate((1000 / x) / size);
                    Pages[k]++;
                });
            };
        }

        public override void Main()
        {
            if (ispublicfile(RequestUri))
                header("Expires", DateTime.MaxValue.ToString());

            var stat = new Stat
            {
                Browser = header("User-Agent"),
                IP = RemoteIP,
                Refer = header("Referer"),
                SessionID = Context.sessionid,
                Time = DateTime.Now,
                Uri = RequestUri
            };

            ThreadPool.QueueUserWorkItem(y => Database.Stat.Save(stat));
        }

        [Route("performance")]
        public void Performance()
        {
            render("Sito.View.Performance",Pages,size);
        }
    }
}
